<template>
	<a-card title="房源管理" :body-style="{ padding: '0' }">
		<!-- 房源列表表格 -->
		<a-table
			:columns="columns"
			:data-source="houses"
			:pagination="false"
			:row-key="record => record.id"
			bordered
		>
			<template #bodyCell="{ column, record }">
				<template v-if="column.key === 'houseImage'">
					<img
						:src="record.houseImages && record.houseImages.length ? record.houseImages[0] : ''"
						alt="房源图片"
						style="width: 120px; height: 100px; object-fit: cover"
					/>
				</template>
				<!-- 房源地址 -->
				<template v-else-if="column.key === 'address'">
					{{ record.address }}
				</template>
				<!-- 房东姓名 -->
				<template v-else-if="column.key === 'landlordName'">
					{{ record.landlordName }}
				</template>
				<!-- 房东联系方式 -->
				<template v-else-if="column.key === 'landlordPhone'">
					{{ record.landlordPhone }}
				</template>
				<!-- 房源状态 -->
				<template v-else-if="column.key === 'houseStatus'">
					{{ getStatus(record.houseStatus) }}
				</template>
				<!-- 房源备注 -->
				<template v-else-if="column.key === 'remarks'">
					{{ record.remarks }}
				</template>
				<!-- 操作列 -->
				<template v-else-if="column.key === 'action'">
					<a @click="goToDetails(record.id)">详情</a>
					<a v-if="record.houseStatus==='available'" style="margin-left: 1rem" @click="openRemoveModal(record)">下架</a>
				</template>
				<!-- 默认展示 -->
				<template v-else>
					{{ record[column.dataIndex] }}
				</template>
			</template>
		</a-table>

		<!-- 分页器 -->
		<a-pagination
			class="pagination"
			:current="pagination.current"
			:page-size="pagination.pageSize"
			:total="pagination.total"
			:page-size-options="['5', '10', '20', '50']"
			@change="handlePageChange"
			@showSizeChange="handlePageSizeChange"
			:show-total="(total, range) => `${range[0]}-${range[1]} 共 ${total} 条`"
			:locale="{ items_per_page: '条/页' }"
		></a-pagination>

		<!-- 下架 Modal -->
		<a-modal
			v-model:visible="removeModalVisible"
			title="下架房源"
			:confirmLoading="removeConfirmLoading"
			@ok="submitRemove"
			@cancel="cancelRemove"
			ok-text="确认下架"
			cancel-text="取消"
			width="400px"
		>
			<a-form layout="vertical">
				<a-form-item label="下架理由">
					<a-textarea
						v-model:value="removeRemarks"
						placeholder="请输入下架理由"
						:rows="3"
					/>
				</a-form-item>
			</a-form>
		</a-modal>
	</a-card>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { message, Modal } from 'ant-design-vue';
import adminApi from '@/api/adminApi';

// -------------------- 列表和分页 --------------------
const houses = ref([]); // 房源列表数据
const pagination = reactive({
	current: 1,
	pageSize: 4,
	total: 0
});

// 表格列配置
const columns = [
	{ title: '房源图片', dataIndex: 'houseImages', key: 'houseImage', width: 120 },
	{ title: '房源地址', dataIndex: 'address', key: 'address', width: 200 },
	{ title: '房东姓名', dataIndex: 'landlordName', key: 'landlordName' },
	{ title: '房东电话', dataIndex: 'landlordPhone', key: 'landlordPhone' },
	{ title: '状态', dataIndex: 'houseStatus', key: 'houseStatus', width: 80 },
	{ title: '备注', dataIndex: 'remarks', key: 'remarks', width: 150 },
	{ title: '操作', dataIndex: 'action', key: 'action', width: 150 }
];

const loadHouses = () => {
	// 调用接口获取所有待审核房源（假设返回的房源状态为 pending、approved、rejected、available、removed 等）
	adminApi.getMyAuditHouses(pagination.current, pagination.pageSize)
		.then(res => {
			if (res.code === 200) {
				houses.value = res.data.houses;
				pagination.total = res.data.total;
			} else {
				message.error(res.message || '查询失败');
			}
		})
		.catch(() => {
			message.error('获取房源数据失败');
		});
};

const handlePageChange = (page) => {
	pagination.current = page;
	loadHouses();
};
const handlePageSizeChange = (current, size) => {
	pagination.pageSize = size;
	pagination.current = 1;
	loadHouses();
};

// 状态转换为中文显示
const getStatus = (status) => {
	const map = {
		pending: '待审核',
		approved: '已通过',
		rejected: '已拒绝',
		available: '已上架',
		removed: '已下架'
	};
	return map[status] || status;
};

// 详情跳转
const goToDetails = (houseId) => {
	window.open(`/house-details/${houseId}`, '_blank');
};

// -------------------- 下架 Modal 相关 --------------------
const removeModalVisible = ref(false);
const removeConfirmLoading = ref(false);
// 用于存储当前准备下架的房源记录
const currentRemoveRecord = ref(null);
// 下架理由
const removeRemarks = ref('');

const openRemoveModal = (record) => {
	currentRemoveRecord.value = record;
	removeRemarks.value = ''; // 清空之前的下架理由
	removeModalVisible.value = true;
};

const submitRemove = () => {
	if (!removeRemarks.value || removeRemarks.value.trim() === '') {
		message.error('请输入下架理由');
		return;
	}
	removeConfirmLoading.value = true;
	// 调用接口更新房源状态为 "removed"，并传递下架理由
	adminApi.removeHouse({
		houseId: currentRemoveRecord.value.id,
		newStatus: 'removed',
		remarks: removeRemarks.value
	})
		.then(res => {
			removeConfirmLoading.value = false;
			if (res.code === 200) {
				message.success('下架成功');
				removeModalVisible.value = false;
				loadHouses();
			} else {
				message.error(res.message || '操作失败');
			}
		})
		.catch(() => {
			removeConfirmLoading.value = false;
			message.error('操作失败，请重试');
		});
};

const cancelRemove = () => {
	removeModalVisible.value = false;
};

onMounted(() => {
	loadHouses();
});
</script>

<style scoped>
.pagination {
	margin: 1rem 0;
	text-align: right;
}
.select-container {
	align-items: center;
	margin: 1rem 0;
	display: flex;
	text-align: center;
	justify-content: flex-end;
	font-size: 15px;
}
</style>
